package com.example.appdemo1.controller;

import com.example.appdemo1.entity.Result;
import com.example.appdemo1.entity.ShopUser;
import com.example.appdemo1.service.ShopUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * 商户控制层
 */
@Controller
public class ShopUserController {
    @Autowired
    private ShopUserService shopUserService;
    @Value("${image.location}")
    private String upload;

    /**
     * 商户入驻功能
     * @param shopUser
     * @param file
     * @return
     */
    @RequestMapping(value = "/saveshop",method = RequestMethod.POST)
    @ResponseBody
    public Result saveShopUser(ShopUser shopUser, MultipartFile file){
        Result rsult = new Result();
        if(file.isEmpty()){
            rsult.setMessage("文件不能为空");
            rsult.setSuccess(false);
            return rsult;
        }
        //实现商户图片上传功能
        UUID uuid = UUID.randomUUID();
        String fileName = file.getOriginalFilename();//获取文件名
        //文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf(".")+1);
        //文件新文件名
        String newFileName = uuid.toString().replace("-","")+"."+suffixName;
        String path = upload+"\\"+newFileName;
        File uploadFile = new File(path);
        try {
            file.transferTo(uploadFile);
            shopUser.setImgUrl(path);
            shopUserService.save(shopUser);
            rsult.setMessage("商户入驻成功");
            rsult.setSuccess(true);
            return rsult;
        }catch (Exception e){
            rsult.setMessage("商户入驻失败");
            rsult.setSuccess(false);
            return rsult;
        }
    }

    /**
     * 根据商户id查询商户信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/finduserbyid/{id}",method = RequestMethod.GET)
    @ResponseBody
    public ShopUser findShopUserById(@PathVariable("id") Integer id){
        return shopUserService.findShopUserById(id);
    }





}
